import { Mark, mergeAttributes } from '@tiptap/core'

export interface CustomMarkOptions {
  HTMLAttributes: Record<string, any>,
}

declare module '@tiptap/core' {
  interface Commands<ReturnType> {
    underline: {
      /**
       * Set an underline mark
       * @example editor.commands.setUnderline()
       */
      setTest: () => ReturnType,
      /**
       * Toggle an underline mark
       * @example editor.commands.toggleUnderline()
       */
      toggleTest: () => ReturnType,
      /**
       * Unset an underline mark
       * @example editor.commands.unsetUnderline()
       */
      unsetTest: () => ReturnType,
    }
  }
}

export const CustomMark = Mark.create<CustomMarkOptions>({
  name: 'underline',

  addOptions() {
    return {
      HTMLAttributes: {},
    }
  },

  parseHTML() {
    return [
      {
        tag: 't2',
      },
      {
        style: 'text-decoration',
        consuming: false,
        getAttrs: style => ((style as string).includes('underline') ? {} : false),
      },
    ]
  },

  renderHTML({ HTMLAttributes }) {
    return ['t2', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]
  },

  addCommands() {
    return {
      setTest: () => ({ commands }) => {
        return commands.setMark(this.name)
      },
      toggleTest: () => ({ commands }) => {
        return commands.toggleMark(this.name)
      },
      unsetTest: () => ({ commands }) => {
        return commands.unsetMark(this.name)
      },
    }
  },

  addKeyboardShortcuts() {
    return {
      'Alt-t': () => this.editor.commands.toggleTest(),
      'Alt-T': () => this.editor.commands.toggleTest(),
    }
  },
})

export default CustomMark
